class SocketResponse {
    constructor() {
        this.socket = null;
    }
    threadSendMsg(agentData) {
        if (!this.socket) return;
        let that = this; // 保存当前对象this

        if (this.socket.readyState === this.socket.OPEN) {
            this.websocketsend(agentData);
        } else if (this.socket.readyState === this.socket.CONNECTING) {
            // 若是 正在开启状态，则等待300毫秒
            setTimeout(function() {
                that.websocketsend(agentData);
            }, 300);
        } else {
            // 若未开启 ，则等待500毫秒
            this.initWebSocket();
            setTimeout(function() {
                that.websocketsend(agentData);
            }, 500);
        }
    }
    initWebSocket() {
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            this.socket = new WebSocket(Config.wsUrl);
            if (!this.socket) return;
            this.socket.onmessage = this.websocketonmessage;
            this.socket.onclose = this.websocketclose;
            this.socket.onerror = this.websocketError;
        } else {
            console.error('browser do not support webscoket!');
        }
    }
    websocketonmessage(e) {
        // 数据接收
        console.log('on message ->', e);
        this.handleOnlineStatus(e.data);
    }
    websocketsend(agentData) {
        // 数据发送
        let params = {
            url: 'DataEncryption',
            data: agentData,
            flag: true,
        };

        Request.requestHandle(params, res => {
            this.socket && this.socket.send(res.data);
        });
    }
    websocketclose(e) {
        // 关闭
        console.log('connection closed (' + e.code + ')->', e);
    }
    websocketError(e) {
        console.error('websocket error!->', e);
        this.$message.error({
            message: 'webscoket服务异常',
        });
    }
}
